const http = require('http');
const socket = require('websocket').server;
const wsPort = 8001;
//http 服务
let server = http.createServer((req,res)=>{
    console.log('new http request to websocket')
});

//websocket握手必须通过http/https协议
let ws = new socket({httpServer: server});
 
ws.on('request', (request)=>{
    request.accept(request.requestedProtocols[0], request.origin)
});
 
ws.on('connect', (connection)=>{
    connection.on('message', (data)=>{
        console.log('client data is: '+ data.data)
    });
 
    connection.on('close', (reason, description)=>{
        console.log('connection is closed, reason code is :'+ reason + ' detail: '+ description)
    })
});

server.listen(wsPort,function(){
    console.log((new Date()) + " ws is listening on port " + wsPort)
});